﻿//
// Copyright (c) 2024 BPer
//
#include <bperutil/BPerAvInfoType.h>
extern "C"{
	#include <bperutil/sys/BPerIni.h>
	#include <bperutil/sys/BPerLog.h>
}

void bPer_context_setMediaConfig(void* context,int32_t puid,BPerAudioParam* audio,BPerVideoParam* video){
	if(context==NULL) return;
	BPerStreamManager* streams=(BPerStreamManager*)context;
	streams->setMediaConfig(puid, audio, video);

}

void bPer_context_sendRequest(void* context,int32_t puid,uint32_t ssrc,BPerRequestType req){
	if(context==NULL) return;
	BPerStreamManager* streams=(BPerStreamManager*)context;
	streams->sendRequest(puid, ssrc, req);
}

class BPerInitContext {
public:
	BPerInitContext() {
	}

	~BPerInitContext() {
	}


};

BPerContext::BPerContext() {
	memset(&rtcCallback,0,sizeof(BPerRtcCallback));
	memset(&sendRtcMessage,0,sizeof(BPerSendRtcMessage));

	streams=new BPerStreamManager(&synMgr);

	rtcCallback.context=streams;
	rtcCallback.setMediaConfig=bPer_context_setMediaConfig;
	rtcCallback.sendRequest=bPer_context_sendRequest;


	bPer_create_synBufferManager(&synMgr);
	init();
#if BPer_OS_ANDROID
	nativeWindow=NULL;
#endif

}

BPerContext::~BPerContext() {
	bPer_closeLogFile();

}
void BPerContext::init(char *filename) {
#if !(BPer_OS_ANDROID || BPer_OS_IOS)
	BPerIni ini;
	ini.filename=NULL;
	bPer_create_ini(&ini,filename);
	//ini.init(filename);
	ini.initAudio(ini.filename,&avinfo.audio);
	ini.initVideo(ini.filename,&avinfo.video);
	ini.initSys(ini.filename,&avinfo.sys);
	ini.initEnc(ini.filename,&avinfo.enc);
	ini.initRtc(ini.filename,&avinfo.rtc);
	initExt(&ini);
	bPer_destroy_ini(&ini);
#else
	bPer_init_avinfo(&avinfo);
#endif

}

void BPerContext::init() {
	bPer_init_avinfo(&avinfo);
	initExt();
}


void BPerContext::initExt() {

}
void BPerContext::initExt(void *filename) {

}

BPerBufferManager::BPerBufferManager() {
	m_curindex = 0;
	m_size = 0;
	m_unitsize = 0;
	m_cache = NULL;
}
BPerBufferManager::BPerBufferManager(int32_t num, int32_t unitsize) {
	m_curindex = 0;
	m_size = 0;
	m_unitsize = 0;
	m_cache = NULL;
	init(num, unitsize);
}
BPerBufferManager::~BPerBufferManager() {
	bPer_deleteA(m_cache);
}

void BPerBufferManager::init(int32_t num, int32_t unitsize) {
	m_size = num;
	m_unitsize = unitsize;
	if (m_cache == NULL)
		m_cache = new uint8_t[m_unitsize * m_size];
}
uint8_t* BPerBufferManager::getBuffer() {
	if (!m_cache)
		return NULL;
	if (m_curindex >= m_size)
		m_curindex = 0;
	return m_cache + m_unitsize * m_curindex++;
}
